import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from query_defects import query_defects

def send_notification(defect_type, confidence):
    # Query the database for notification configuration
    db_defects = query_defects(image_keyword=None)
    for defect in db_defects:
        if defect[1] == defect_type and confidence >= defect[2]:
            notification_method = defect[3]
            notify_to = defect[4]
            if notification_method == 'Email':
                send_email(notify_to, defect_type, confidence, defect[2])

def send_email(to_email, defect_type, confidence, severity_threshold):
    # Email configuration
    sender_email = "your_email@example.com"
    sender_password = "your_email_password"
    smtp_server = "smtp.example.com"
    smtp_port = 587
    
    # Create the email message
    subject = f"Defect Detection Alert: {defect_type}"
    body = f"""
    A defect of type '{defect_type}' has been detected with a confidence level of {confidence}.
    The severity threshold for this defect type is {severity_threshold}.
    """
    
    msg = MIMEMultipart()
    msg['From'] = sender_email
    msg['To'] = to_email
    msg['Subject'] = subject
    
    msg.attach(MIMEText(body, 'plain'))
    
    try:
        # Connect to the SMTP server and send the email
        server = smtplib.SMTP(smtp_server, smtp_port)
        server.starttls()
        server.login(sender_email, sender_password)
        server.sendmail(sender_email, to_email, msg.as_string())
        server.quit()
        print(f"Email sent to {to_email}")
    except Exception as e:
        print(f"Failed to send email: {e}")
